package com.myway.javafx.controller;

import com.myway.javafx.entity.GitPro;
import com.myway.javafx.service.Base64Service;
import com.myway.javafx.service.GitService;
import com.myway.javafx.service.PwdService;
import com.myway.javafx.util.DESCrypts;
import com.myway.tools.security.Sm3Utils;
import javafx.application.Platform;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Component
public class MainController {

    public TextArea txtBase64;//编码后
    public TextArea txtSource;//编码前

    public TextArea pwdSource;//加密前
    public TextArea pwdCode;//加密后
    public Button encryptBtn;//加密
    public Button decryptBtn;//解密

    public Button btnFile;//选择文件按钮
    public TextField wordpath;//文件路径
    public TextArea wordlog;//文件转换日志
    public Button fileToImage;//开始转换文件
    public Button clearFile;
    public ToggleGroup pwd;

    public TextField downpath;//下载路径
    public Button export;
    public TextArea downlog;//下载日志

    @Autowired
    private Base64Service base64Service;
    @Autowired
    private PwdService pwdService;
    @Autowired
    private GitService gitService;
    private String filePath = "";

    public void initialize() {
        this.txtSource.textProperty().addListener((observable, oldValue, newValue) -> {
            this.txtBase64.setText(parseBase64(newValue));
        });

        this.encryptBtn.setOnAction(event -> {
            String text = pwdSource.getText();
            if(text.length()>0){
                String userData = pwd.getSelectedToggle().getUserData().toString();
                if("网站".equals(userData)){
                    this.pwdCode.setText(encryptPwd(text));
                }else if("SM3".equals(userData)){
                    this.pwdCode.setText(Sm3Utils.encrypt(text));
                }else{
                    this.pwdCode.setText(DESCrypts.Encrypt(text));
                }
            }else{
                this.pwdCode.setText("");
            }
        });
        this.decryptBtn.setOnAction(event -> {
            String text = pwdCode.getText();
            if(text.length()>0){
                if("网站".equals(pwd.getSelectedToggle().getUserData().toString())){
                    this.pwdSource.setText(decryptPwd(text));
                }else{
                    this.pwdSource.setText(DESCrypts.Decrypt(text));
                }
            }else{
                this.pwdSource.setText("");
            }
        });
        btnFile.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("Word Files", "*.doc", "*.docx")
            );
            fileChooser.setTitle("请选择一个word");
            Stage selectFile = new Stage();
            File file = fileChooser.showOpenDialog(selectFile);
            if (file != null) {
                filePath = file.getPath();
                String fileName = file.getName();
                String fileName_lower = fileName.toLowerCase();
                if (fileName_lower.endsWith(".doc") || fileName_lower.endsWith(".docx")) {
                    this.wordpath.setText(fileName);
                } else {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.titleProperty().set("提示");
                    alert.headerTextProperty().set("请选择一个word文档");
                    alert.showAndWait();
                }
            }
        });
        fileToImage.setOnAction(event -> {
            if (filePath != "") {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.titleProperty().set("提示");
                alert.headerTextProperty().set("是否开始转换 " + this.wordpath.getText());

                Optional<ButtonType> result = alert.showAndWait();
                if (result.get() == ButtonType.OK) {
                    this.wordlog.appendText(new Random().nextInt(100) + "\r\n");
                }
            }
        });
        clearFile.setOnAction(event -> {
            this.wordpath.setText("");
            this.wordlog.setText("");
            this.filePath = "";
        });
        downpath.setOnMouseClicked(event -> {
            Stage selectFile = new Stage();
            DirectoryChooser directoryChooser=new DirectoryChooser();
            File file = directoryChooser.showDialog(selectFile);
            String path = file.getPath();//选择的文件夹路径
            downpath.setText(path);
        });
        export.setOnAction(event -> {
            if(StringUtils.hasText(downpath.getText())){
                startDown();
            }else {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.titleProperty().set("提示");
                alert.headerTextProperty().set("请选择下载路径");
                alert.showAndWait();
            }
        });
    }

    private String encryptPwd(String s) {
        if (s.length() == 0) {
            return "";
        }
        LocalTime now = LocalTime.now();
        return pwdService.encryptPwd((now.getHour() * 3600 + now.getMinute() * 60 + now.getSecond()) + "," + s);
    }
    private String decryptPwd(String s) {
        if (s.length() == 0) {
            return "";
        }
        return pwdService.decryptPwd(s);
    }

    private String parseBase64(String s) {
        if (s.length() == 0) {
            return "";
        }
        return base64Service.parseBase64(s);
    }
    private void startDown(){
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                try {
                    gitService.findAllPros(downlog,downpath.getText());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
